<template>
  <div>
    <zh-table
        ref="tableListRef"
        title="form组件列表"
        :height="700"
        type="default"
        show-overflow
        keep-source
        :data="state.tableData"
        :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
        :columns="state.tableColumn"
        :show-header-overflow="false"
        :column-config="{resizable: true}"
        :tree-config="{children: 'children', rowField: 'formParamsId', parentField: 'parentId'}"
        :disabled="false"
        :scrollY="{enabled: false}"
        :stripe="false"
        :draggable="true"
        @row-drag-change="onChange"
        :row-config="{keyField: 'formParamsId'}"
        highlight-current-row
    >
      <template #type_default="{ row }">
        {{ row.typeName }}
      </template>
      <template #type_edit="{ row }">
        <zh-ele-select v-model="row.type" @change="onTypeChange($event,row)" :options="state.dictData.FORMPARAMTYPE"></zh-ele-select>
      </template>
      <template #field_edit="{ row }">
        <zh-input v-model="row.field"  @change="onChange"></zh-input>
      </template>
      <template #title_edit="{ row }">
        <zh-input v-model="row.title"  @change="onChange"></zh-input>
      </template>
      <template #info_edit="{ row }">
        <zh-input v-model="row.info"  @change="onChange"></zh-input>
      </template>
      <template #col_edit="{ row }">
        <zh-input v-model="row.col"  @change="onChange"></zh-input>
      </template>
      <template #header_button>
        <zh-button button-type="add" v-func:excelModel0108 @click="addParam()">新增字段</zh-button>
      </template>
      <template #operate_default="{ row }">
        <el-tooltip
            effect="dark"
            content="下级插入字段"
            placement="top"
        >
          <zh-button v-func:excelModel0108 button-type="add" link @click="addChildParam(row)"></zh-button>
        </el-tooltip>
        <el-tooltip
            effect="dark"
            content="删除字段"
            placement="top"
        >
          <zh-button v-func:excelModel0108 type="danger" icon="ele-Minus" link @click="delParam(row)"></zh-button>
        </el-tooltip>

      </template>
    </zh-table>
  </div>
</template>
<script lang="ts" setup name="FormParamsForm">
import { ElMessage } from 'element-plus';
import { uuid } from '@/utils/util';
//------------------接收传入参数(组件)-------------------
const props = defineProps({
  modelInfo: {
    type: Object,
    default: () => {},
    required: false,
  },
  modelValue: Boolean,
});
//------------------定义子组件---------------------------
const tableListRef=ref();
//------------------内部变量定义-------------------------
const state=reactive({
  tableData:[
    // { formParamsId: 10000, id: 10000, parentId: null, name: 'vxe-table test abc1', type: 'mp3', size: 1024, date: '2020-08-01' },
    // { formParamsId: 10050, id: 10050, parentId: null, name: 'Test2', type: 'mp4', size: null, date: '2021-04-01' },
    // { formParamsId: 24300, id: 24300, parentId: 10050, name: 'Test3', type: 'avi', size: 1024, date: '2020-03-01' },
    // { formParamsId: 20045, id: 20045, parentId: 24300, name: 'vxe-table test abc4', type: 'html', size: 600, date: '2021-04-01' },
    //   {formParamsId: '1', parentId: null, field: '1', type: 'Input', typeName: '输入框', children: [
    //       {formParamsId: '2', parentId: '1', field: '2', type: 'Input', typeName: '输入框'},
    //       {formParamsId: '3', parentId: '1', field: '3', type: 'Input', typeName: '输入框'},
    //     ]},

  ],
  canSave:false,
  insertList:[],
  dictData:{},
  tableColumn:[
    { field: 'formParamsId', title: '字段id', visible: false, editRender:{},align: 'left', width: 200},
    { field: 'type', title: '类型', treeNode:'true', editRender:{}, align: 'center', width: 200,slots: {default: 'type_default', edit: 'type_edit'} },
    { field: 'field', title: '字段名称',  editRender:{}, align: 'center', width: 200,slots: {edit: 'field_edit'} },
    { field: 'title', title: '名称',  editRender:{}, align: 'center', width: 200,slots: {edit: 'title_edit'} },
    { field: 'info', title: '提示信息', align: 'center', editRender:{},  width: 150,slots: {edit: 'info_edit'}},
    { field: 'col', title: '占用宽度', align: 'center', editRender:{},  width: 150,slots: {edit: 'col_edit'}},
    { field: 'operate', title: '操作', align: 'center',fixed: 'right',  width: 100,slots: {default: 'operate_default'}},
  ]
})
//------------------定义调用方法-------------------------
const onTypeChange=(val,row)=>{
  let dictList=state.dictData.FORMPARAMTYPE.filter(item => item.dictKey === val)
  if(dictList&&dictList.length>0){
    row.typeName=dictList[0].dictValue
  }
  state.canSave=true
}
const onChange=()=>{
  state.canSave=true
}
const addParam=()=>{
  //新增
  let id=uuid()
  let params={formParamsId: id, type: '', field: '', title: '', info: '',parentId: null, children:[]}
  let tableData=[...state.tableData]
  tableData.push(params)
  state.tableData=tableData
  state.insertList.push(id)
}
const addChildParam=(row)=>{
  //子级新增
  if(!row.formParamsId){
    ElMessage.error('字段类型为空，不能创建子节点');
    return;
  }
  let id=uuid()
  let params={formParamsId:id, parentId:row.formParamsId}
  let children=row.children||[]
  children.push(params);
  row.children=children
  state.tableData=[...state.tableData]
  tableListRef.value.setTreeExpand(row, true)
  state.insertList.push(id)
  console.log('state.tableData', state.tableData);
}
const delParam=(row)=>{
  //删除字段
  let list=[...state.tableData]
  delParamByRow(row,list);
  state.tableData=list;
  let deleteIndex=state.insertList.indexOf(row.id);
  state.insertList.splice(deleteIndex, 1)
  if(deleteIndex<0){
    state.canSave=true;
  }
}
const delParamByRow=(row,list)=>{
  for (let i = 0, len = list.length; i < len; i++) {
    let item=list[i]
    if(item.id === row.id){
      list.splice(i, 1)
      break;
    }else{
      if(item.children&&item.children.length>0){
        delParamByRow(row,item.children)
      }
    }
  }

}
const queryTable=()=>{
  //查询模版字段
  setTimeout(() => {
    let params={formId:props.modelInfo.formId}
    $api.common.send.post('formInfoParams0008', params).then((res) => {
      state.tableData = res.result||[];
    });
  }, 20);
}
const isEdit=()=>{
  //判断是否做过信息变动
  let canSave=state.canSave;
  let updateList=tableListRef.value.getUpdateRecords();
  if(updateList&&updateList.length>0){
    canSave=true;
  }
  if(state.insertList.length>0){
    canSave=true;
  }
  return canSave;
}
const save=()=>{
  //保存方法
  if(!state.tableData||state.tableData.length<=0){
    ElMessage.error('数据为空，不能保存');
    return;
  }

  if(!isEdit()){
    ElMessage.error('没有字段信息变动，不能保存');
    return;
  }
  let list=tableListRef.value.getTableData().tableData;
  for (let formInfoParams of list) {
    customComponentCast(formInfoParams);
  }
  let params={formId:props.modelInfo.formId,list:list}
  $api.common.send.post('formInfoParams0007', params).then(() => {
    reset();
    ElMessage.success('保存成功！');
  });
}
const reset=()=>{
  //重置数据
  queryTable();
  state.canSave=false;
  state.insertList=[]
}
const customComponentCast = (formInfoParams) => {
  if (formInfoParams.type.indexOf('zh-') != -1 && formInfoParams.col) {
    if (!formInfoParams.props) {
      formInfoParams.props = {};
    }
    else if (typeof(formInfoParams.props) == 'string') {
      formInfoParams.props = JSON.parse(formInfoParams.props);
    }

    Object.assign(formInfoParams.props, {span: Number.parseInt(formInfoParams.col)});
    formInfoParams.props = JSON.stringify(formInfoParams.props);
  }
  if (!formInfoParams.children) {
    return;
  }
  for (let childFormInfoParams of formInfoParams.children) {
    customComponentCast(childFormInfoParams);
  }
}
//------------------初始化------------------------------
onMounted(()=>{
  queryTable();
  initDict();
})
const initDict=()=>{
  const params = {
    dictFields: 'FORMPARAMTYPE',
  };
  $api.common.getBatchDict.post(params).then((res) => {
    state.dictData = res.result;
  });
}
//------------设置给父组件调用的数据/方法(组件)-----------
defineExpose({ form: state.form ,save,reset,isEdit});
</script>
<style lang="scss" scoped></style>
